from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import os
from werkzeug.utils import secure_filename
from openai import OpenAI
from docx import Document
import PyPDF2
from pptx import Presentation

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = {'pdf', 'ppt', 'pptx', 'doc', 'docx'}
TEMPLATE_PATH = '../training_plan_template.docx'
DEEPSEEK_API_KEY = 'sk-d7add522c81c41a1961e46aee27e0016'

app = Flask(__name__)
CORS(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(filepath)
        return jsonify({'filename': filename}), 200
    else:
        return jsonify({'error': 'File type not allowed'}), 400

def parse_docx(filepath):
    doc = Document(filepath)
    text = []
    for para in doc.paragraphs:
        if para.text.strip():
            text.append(para.text)
    return '\n'.join(text)

def parse_pdf(filepath):
    text = []
    with open(filepath, 'rb') as f:
        reader = PyPDF2.PdfReader(f)
        for page in reader.pages:
            page_text = page.extract_text()
            if page_text:
                text.append(page_text)
    return '\n'.join(text)

def parse_pptx(filepath):
    prs = Presentation(filepath)
    text = []
    for slide in prs.slides:
        for shape in slide.shapes:
            if hasattr(shape, "text"):
                if shape.text.strip():
                    text.append(shape.text)
    return '\n'.join(text)

def parse_file(filepath):
    ext = filepath.rsplit('.', 1)[1].lower()
    if ext in ['doc', 'docx']:
        return parse_docx(filepath)
    elif ext == 'pdf':
        return parse_pdf(filepath)
    elif ext in ['ppt', 'pptx']:
        return parse_pptx(filepath)
    else:
        return ''

# DeepSeek API 调用
client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com")

def call_deepseek(prompt):
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "你是一个智能教案生成助手"},
            {"role": "user", "content": prompt},
        ],
        stream=False
    )
    return response.choices[0].message.content

@app.route('/generate', methods=['POST'])
def generate_plan():
    data = request.json
    filename = data.get('filename')
    course_title = data.get('course_title', '')
    if not filename:
        return jsonify({'error': 'No filename provided'}), 400
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    if not os.path.exists(filepath):
        return jsonify({'error': 'File not found'}), 404
    # 解析课件内容
    content = parse_file(filepath)
    # 构造 prompt
    prompt = f"请根据以下课件内容和课程标题，结合教案模板，生成详细教案。\n课件内容：{content}\n课程标题：{course_title}"
    # 调用 DeepSeek
    plan = call_deepseek(prompt)
    # TODO: 根据模板生成 Word 文件（可用 python-docx）
    output_path = os.path.join(app.config['UPLOAD_FOLDER'], 'generated_plan.docx')
    # 这里只是保存纯文本，后续可完善为填充模板
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(plan)
    return jsonify({'download_url': '/download/generated_plan.docx'})

@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    if not os.path.exists(filepath):
        return jsonify({'error': 'File not found'}), 404
    return send_file(filepath, as_attachment=True)

if __name__ == '__main__':
    print('Flask 服务已启动')
    app.run(debug=True, host='0.0.0.0', port=5000) 